package com.epigeon.amadeo.test2;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.epigeon.amadeo.engine.Engine;
import com.epigeon.amadeo.impl.ActiveList;
import com.epigeon.amadeo.model.Message;
import com.epigeon.amadeo.model.StringMessage;
import com.epigeon.amadeo.test2.R;

public class MyActiveList extends ActiveList {

	public static final String MESSAGE_TYPE_DELETE = "deleteFromList";
	public static final String MESSAGE_TYPE_ADD = "addToList";

	private List<String> continut = new LinkedList<String>();

	private int lastLongSelectedItemIndex = -1;	
	
	public MyActiveList(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		this.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				lastLongSelectedItemIndex = arg2;
				update();
				return true;
			}
			
		});		
	}

	public int getLastSelectedItemIndex() {
		return this.lastLongSelectedItemIndex;
	}
	
	public void update() {
		message = new StringMessage(MyActiveList.MESSAGE_TYPE_DELETE, this.getKey(), Integer.toString(this.getLastSelectedItemIndex())); 		
		Engine.getInstance().activeInputNotification(this, message);		
	}
	
	public void putMessage(Message message) {
		if ( MyActiveList.MESSAGE_TYPE_ADD.equals(message.getType()) ) {
			StringMessage stringMessage = (StringMessage) message;
			continut.add(stringMessage.getValue());
			this.setAdapter(new ArrayAdapter<String>(this.getContext(), R.layout.row, continut));
		} else if ( MyActiveList.MESSAGE_TYPE_DELETE.equals(message.getType()) ) {
			StringMessage stringMessage = (StringMessage) message;			
			continut.remove(Integer.parseInt(stringMessage.getValue()));
			this.setAdapter(new ArrayAdapter<String>(this.getContext(), R.layout.row, continut));			
		}		
	}

	@Override
	public Message compose(List<Message> messages) {
		// no need to call compose so null is passed
		return null;
	}

	@Override
	public void setParameters(Map<String, String> parameterMap) {
		// nothing to do here
	}
	
}
